﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace HMS.Security
{
    public class CookieEncryption
    {
        private static string key = "sfdjf48mdfdf3054" ;

        public CookieEncryption()
		{
		}

		public static string Encrypt(String plainText )
		{
			string encrypted = null;
			try
			{
				byte[] inputBytes = ASCIIEncoding.ASCII.GetBytes(plainText);
				byte[] pwdhash = null;
				MD5CryptoServiceProvider hashmd5;

				//generate an MD5 hash from the password. 
				//a hash is a one way encryption meaning once you generate
				//the hash, you cant derive the password back from it.
				hashmd5 = new MD5CryptoServiceProvider();
				pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
				hashmd5 = null;

				// Create a new TripleDES service provider 
				TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
				tdesProvider.Key = pwdhash;
				tdesProvider.Mode = CipherMode.ECB;

				encrypted = Convert.ToBase64String(
					tdesProvider.CreateEncryptor().TransformFinalBlock(inputBytes, 0, inputBytes.Length));
			}
			catch(Exception e)
			{
				string str = e.Message;
				throw ;
			}
			return encrypted;
		}

		public static String Decrypt(string encryptedString)
		{
			string decyprted = null;
			byte[] inputBytes = null;

			try
			{
				inputBytes = Convert.FromBase64String(encryptedString);
				byte[] pwdhash = null;
				MD5CryptoServiceProvider hashmd5;

				//generate an MD5 hash from the password. 
				//a hash is a one way encryption meaning once you generate
				//the hash, you cant derive the password back from it.
				hashmd5 = new MD5CryptoServiceProvider();
				pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
				hashmd5 = null;

				// Create a new TripleDES service provider 
				TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
				tdesProvider.Key = pwdhash;
				tdesProvider.Mode = CipherMode.ECB;

				decyprted = ASCIIEncoding.ASCII.GetString(
					tdesProvider.CreateDecryptor().TransformFinalBlock(inputBytes, 0, inputBytes.Length));
			}
			catch(Exception e)
			{
				string str = e.Message;
				throw ;
			}
			return decyprted;
		}
    }
    public class PassowdEncryption
    {
       
        public byte[] GetEncryptedPassword(string strPassword, string strEncryptType)
        {
            byte[] bytPassword = null;
            if (strEncryptType == "MD5")
            {
                MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
                UTF8Encoding encoder = new UTF8Encoding();
                bytPassword = md5Hasher.ComputeHash(encoder.GetBytes(strPassword));
            }
            else
            {
                string plainText = null;
                string passPhrase = null;
                string saltValue = null;
                string hashAlgorithm = null;
                int passwordIterations = 0;
                string initVector = null;
                int keySize = 0;

                plainText = strPassword;
                // original plaintext
                passPhrase = "Pas5pr@se";
                // can be any string
                saltValue = "s@1tValue";
                // can be any string
                hashAlgorithm = "SHA1";
                // can be "MD5"
                passwordIterations = 2;
                // can be any number
                initVector = "@1B2c3D4e5F6g7H8";
                // must be 16 bytes
                //keySize = Conversion.Val(strEncryptType);
                keySize = Convert.ToInt32(strEncryptType);

                // can be 128 or 192 or 256

                bytPassword = Encrypt(plainText, passPhrase, saltValue, hashAlgorithm, passwordIterations, initVector, keySize);
            }
            return bytPassword;
        }

        private byte[] Encrypt(string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
        {

            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8 
            // encoding.
            byte[] initVectorBytes = null;
            initVectorBytes = Encoding.ASCII.GetBytes(initVector);

            byte[] saltValueBytes = null;
            saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = null;
            plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // First, we must create a password, from which the key will be derived.
            // This password will be generated from the specified passphrase and 
            // salt value. The password will be created using the specified hash 
            // algorithm. Password creation can be done in several iterations.
            PasswordDeriveBytes password = default(PasswordDeriveBytes);
            password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = null;
            keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = default(RijndaelManaged);
            symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate encryptor from the existing key bytes and initialization 
            // vector. Key size will be defined based on the number of the key 
            // bytes.
            ICryptoTransform encryptor = default(ICryptoTransform);
            encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = default(MemoryStream);
            memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = default(CryptoStream);
            cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
            // Start encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] cipherTextBytes = null;
            cipherTextBytes = memoryStream.ToArray();

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert encrypted data into a base64-encoded string.
            string cipherText = null;
            cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return cipherTextBytes;
        }
    }

}
